package cn.waka.sys.admin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.waka.sys.admin.object.Result;
import cn.waka.sys.admin.object.WechatConfig;
import cn.waka.sys.admin.service.WechatConfigService;
import cn.waka.sys.admin.utils.SignUtil;

/**
 * @author zhuzhsh
 * 微信公众号消息处理
 */
@Controller
@RequestMapping("/wechat")
public class WxConfigController extends BaseController {

	private final static Logger log = LoggerFactory.getLogger(WxConfigController.class);
	@Autowired
	private WechatConfigService service;
	
	@RequestMapping("config/index")
	public ModelAndView configIndex() {
		ModelAndView mv=new ModelAndView("");
		return mv;
	}
	
	@RequestMapping("config/save")
	public Result configSave() {
		
		
		return this.ok();
	}
	
	@RequestMapping("msg/{appid}")
	public void config(@PathVariable(value = "appid", required = false) String appid, String signature,
			String timestamp, String nonce, HttpServletRequest request, HttpServletResponse response) {
		if (appid == null || appid.length() == 0) {
			return;
		}

		WechatConfig config = service.findById(appid);
		if (config == null) {
			return;
		}
		if (log.isDebugEnabled()) {
			log.debug("=====公众号:" + config.getName());
		}
		String method = request.getMethod();
		if ("POST".equals(method)) {
			String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ? "raw"
					: request.getParameter("encrypt_type");
			if (log.isDebugEnabled()) {
				log.debug("========EncryptType:" + encryptType);
			}
			if ("raw".equals(encryptType)) {
				// 明文传输的消息
				service.replyMsg(request, response);
				// return;
			} else if ("aes".equals(encryptType)) {
				service.replyMsg(request, response);
			}

		} else {
			String echostr = request.getParameter("echostr");
			if (echostr == null || echostr.length() == 0) {
				return;
			}
			boolean checked = SignUtil.checkSignature(config, signature, timestamp, nonce);
			if (checked) {
				this.write(response, echostr);
			} else {
				this.write(response, "");
			}
		}

	}

	public void setService(WechatConfigService service) {
		this.service = service;
	}

}
